﻿$(function () {
    'use strict';

    var pageIndex = 0;
    var loading = false;

    function loadGridData(url, page, callback) {
        loading = true;
        $.get(url, { page: pageIndex }, function (result) {
            if (result.trim() == '') {
                $.detachInfiniteScroll($(page).find('.infinite-scroll'));
                $(page).find('.infinite-scroll-preloader').hide();
            } else {
                $(page).find('.list-block ul').append(result);
                pageIndex++;
            }
            if (callback) {
                callback();
            }
            loading = false;
        });
    }

    function refreshGridCallback(page) {
        $.pullToRefreshDone('.pull-to-refresh-content');
        $.attachInfiniteScroll($(page).find('.infinite-scroll'));
        $(page).find('.infinite-scroll-preloader').show();
    }

    function gridInit(page) {
        pageIndex = 2;
        loading = false;
        var url = $(page).find('.list-block').data('url');

        $(document).on('refresh', '.pull-to-refresh-content', function () {
            pageIndex = 1;
            $(page).find('.list-block ul').empty();
            loadGridData(url, page, function () {
                refreshGridCallback(page);
            });
        });

        $(document).on('infinite', '.infinite-scroll', function () {
            if (loading) return;
            loadGridData(url, page);
        });
        if ($(page).find('.list-block li').length < 9) {
            $(page).find('.infinite-scroll-preloader').hide();
        }
    }

    //#region page-fav-quest

    $(document).on('pageInit', '#page-fav-quest', function (e, id, page) {

        var questArea = $(page).find('#questArea');

        function questDelete(url) {
            $.confirm('确定要删除当前题吗?', function () {
                $.ajax({
                    url: url,
                    success: function (result) {
                        if (result.success) {
                            questInit(questArea.data('url'));
                        } else {
                            $.alert(result.message);
                        }
                    }
                });
            });
        };

        function questInit(url) {
            $.ajax({
                url: url,
                dataType: 'html',
                success: function (result) {

                    questArea.empty().html(result);

                    $(page).find('#record-count').html(questArea.find('#correct-answer').data('count'));

                    questArea.find('#btn-answer').click(function () {
                        var answer = questArea.find('#correct-answer');
                        if (answer.css('display') == 'none') {
                            answer.css('display', 'block');
                        } else {
                            answer.css('display', 'none');
                        }
                    });

                    questArea.find('#btn-delete').click(function () {
                        questDelete($(this).data('url'));
                    });

                    questArea.find('#btn-prve').click(function () {
                        questInit($(this).data('url'));
                    });

                    questArea.find('#btn-next').click(function () {
                        questInit($(this).data('url'));
                    });
                }
            });
        };

        questInit(questArea.data('url'));
    });

    //#endregion

    //#region page-exercise-quest

    $(document).on('pageInit', '#page-exercise-quest', function (e, id, page) {

        var questArea = $(page).find('#questArea');

        function questFavorite(btn) {
            var url = $(btn).data('url');
            var isFavorite = $(btn).attr('favorite') == '0';
            $.ajax({
                url: url,
                data: { isFavorite: isFavorite },
                success: function (result) {
                    if (result.success) {
                        if (isFavorite) {
                            $(btn).attr('favorite', '1');
                            $(btn).find('span:eq(1)').html('已收藏');
                            $(btn).addClass('button-fill');
                        } else {
                            $(btn).attr('favorite', '0');
                            $(btn).find('span:eq(1)').html('收藏');
                            $(btn).removeClass('button-fill');
                        }
                    } else {
                        fx.alert(result.message);
                    }
                }
            });
        };

        function questChecked() {
            var user_value = $(this).val();
            var correct_value = questArea.find('#correctAnswer').val();
            var result = false;
            if (user_value == correct_value) { //回答正确
                result = true;
                questArea.find('#answer_yes').css('display', 'block');
                questArea.find('#answer_no').hide();
            } else { //回答错误
                result = false;
                questArea.find('#answer_yes').hide();
                questArea.find('#answer_no').css('display', 'block');
            }
            //记录答题情况
            var check_url = questArea.find('#correctAnswer').data('url');
            $.ajax({
                data: { userResult: result, userAnswer: user_value },
                url: check_url
            });
            questArea.find('input[type="radio"]').iCheck('disable');
        };

        function questMxChecked() {
            var user_value = '';
            var correct_value = questArea.find('#correctAnswer').val();
            questArea.find('.uicheck:checked').each(function (i, v) {
                user_value += v.value;
            });
            user_value = user_value.toLocaleUpperCase().split('').sort().join('');
            correct_value = correct_value.toLocaleUpperCase().split('').sort().join('');

            var result = false;
            if (user_value == correct_value) { //回答正确
                result = true;
                questArea.find('#answer_yes').css('display', 'block');
                questArea.find('#answer_no').hide();
            } else { //回答错误
                result = false;
                questArea.find('#answer_yes').hide();
                questArea.find('#answer_no').css('display', 'block');
            }
            //记录答题情况
            var check_url = questArea.find('#correctAnswer').data('url');
            $.ajax({
                data: { userResult: result, userAnswer: user_value },
                url: check_url
            });
            questArea.find('#btn_answer_submit').hide();
            questArea.find('input[type="checkbox"]').iCheck('disable');
        };

        function questInit(url) {
            $.ajax({
                url: url,
                dataType: 'html',
                success: function (result) {

                    questArea.empty().html(result);

                    $(page).find('#record-count').html(questArea.find('#correctAnswer').data('current') + '/' + questArea.find('#correctAnswer').data('count'));

                    questArea.find('.uicheck').iCheck({
                        checkboxClass: 'icheckbox_square-blue',
                        radioClass: 'iradio_square-blue',
                        increaseArea: '20%' // optional
                    });

                    $('#cmdbar').css('top',$('#questArea').height()+140);

                    questArea.find('input[type="radio"]').on('ifChecked', questChecked);

                    questArea.find('#btn_answer_submit').click(function () {
                        questMxChecked();
                    });

                    questArea.find('#btn-favorite').click(function () {
                        questFavorite(this);
                    });

                    questArea.find('#btn-prve').click(function () {
                        questInit($(this).data('url'));
                    });

                    questArea.find('#btn-next').click(function () {
                        questInit($(this).data('url'));
                    });
                }
            });
        };

        questInit(questArea.data('url'));
    });

    //#endregion

    //#region page-exam-quest

    $(document).on('pageInit', '#page-exam-quest', function (e, id, page) {

        var isInit = false;
        var surplusSecond = 5400;
        var okScore = 80;
        var questArea = $(page).find('#questArea');

        function questChecked() {
            var user_value = $(this).val();
            var correct_value = questArea.find('#correctAnswer').val();
            var result = false;
            if (user_value == correct_value) { //回答正确
                result = true;
                questArea.find('#answer_yes').css('display', 'block');
                questArea.find('#answer_no').hide();
            } else { //回答错误
                result = false;
                questArea.find('#answer_yes').hide();
                questArea.find('#answer_no').css('display', 'block');
            }
            //记录答题情况
            var check_url = questArea.find('#correctAnswer').data('url');
            $.ajax({
                data: { userResult: result, userAnswer: user_value },
                url: check_url,
                success: function () {
                    if ($('#btn-next').length > 0) {
                        var init_url = $('#btn-next').data('url');
                        questInit(init_url);
                    }
                }
            });
            questArea.find('input[type="radio"]').iCheck('disable');
        };

        function questMxChecked() {
            var user_value = '';
            var correct_value = questArea.find('#correctAnswer').val();
            questArea.find('.uicheck:checked').each(function (i, v) {
                user_value += v.value;
            });
            user_value = user_value.toLocaleUpperCase().split('').sort().join('');
            correct_value = correct_value.toLocaleUpperCase().split('').sort().join('');

            var result = false;
            if (user_value == correct_value) { //回答正确
                result = true;
                questArea.find('#answer_yes').css('display', 'block');
                questArea.find('#answer_no').hide();
            } else { //回答错误
                result = false;
                questArea.find('#answer_yes').hide();
                questArea.find('#answer_no').css('display', 'block');
            }
            //记录答题情况
            var check_url = questArea.find('#correctAnswer').data('url');
            $.ajax({
                data: { userResult: result, userAnswer: user_value },
                url: check_url,
                success: function () {
                    if ($('#btn-next').length > 0) {
                        var init_url = $('#btn-next').data('url');
                        questInit(init_url);
                    }
                }
            });
            questArea.find('#btn_answer_submit').hide();
            questArea.find('input[type="checkbox"]').iCheck('disable');
        };

        function questCommit() {
            $.confirm('确定交卷吗？', function () {
                var url = $('#btn-commit').data('url');
                $.ajax({
                    url: url,
                    success: function (result) {
                        pauseCount();
                        $('.answer_btn').remove();
                        $('#pause_quest').remove();
                        $('#commit_quest').remove();

                        var totalScore = result.totalScore;
                        var totalCount = result.totalCount;
                        var correctCount = result.correctCount;
                        var errorCount = result.errorCount;
                        var userScore = result.userScore;
                        var isOk = userScore > okScore;
                        var msg = isOk ? '恭喜,通过考核' : '很遗憾,未能通过考核';
                        var tpl =
                        '<p class="exam_question_result_title">' +
                            '得分:' + userScore + '分' +
                            '</p>' +
                            '<p>' + msg + '</p>' +
                            '<p class="exam_question_result_content">' +
                            '共:<span class="exam_question_result_number">' + totalCount + '</span>题 ' +
                            '正确:<span class="exam_question_result_number">' + correctCount + '</span>题 ' +
                            '错误:<span class="exam_question_result_number">' + errorCount + '</span>题' +
                            '</p>';
                        $.alert(tpl, function () {
                            var u = $(page).find('#currentQuestionUrl').data('url');
                            questInit(u);
                        });
                    }
                });
            });
        };

        //显示倒计时
        function ShowCountDown() {
            if (surplusSecond < 1) {
                $(page).find('#remainingTime').html('00:00');
                window.clearInterval(window.jsq);
                questCommit();
                return;
            }

            surplusSecond = surplusSecond - 1;
            var min = Math.floor(surplusSecond / 60);
            if (min < 1) {
                min = 0;
            }
            var sec = surplusSecond % 60; // 这是取模
            if (min < 10) {
                min = '0' + min;
            }

            if (sec < 10) {
                sec = '0' + sec;
            }
            $(page).find('#remainingTime').html(min + ':' + sec);
        };

        function pauseCount() {
            if (window.jsq) {
                window.clearInterval(window.jsq);
                window.jsq = null;
            }
        }

        function startCount() {
            if (!window.jsq) {
                window.jsq = window.setInterval(function () { ShowCountDown(); }, 1000);
            }
        }

        function questInit(url) {
            $.ajax({
                url: url,
                dataType: 'html',
                success: function (result) {

                    questArea.empty().html(result);

                    $(page).find('#record-count').html(questArea.find('#correctAnswer').data('current') + '/' + questArea.find('#correctAnswer').data('count'));

                    questArea.find('.uicheck').iCheck({
                        checkboxClass: 'icheckbox_square-blue',
                        radioClass: 'iradio_square-blue',
                        increaseArea: '20%' // optional
                    });

                    if ($('#answer_yes').length == 1 || $('#answer_no').length == 1) {
                        $('#cmdbar').css('top',$('#questArea').height()+55);
                    }

                    questArea.find('input[type="radio"]').on('ifChecked', questChecked);

                    questArea.find('#btn_answer_submit').click(function () {
                        questMxChecked();
                    });

                    questArea.find('#btn-commit').click(function () {
                        questCommit();
                    });

                    questArea.find('#btn-prve').click(function () {
                        questInit($(this).data('url'));
                    });

                    questArea.find('#btn-next').click(function () {
                        questInit($(this).data('url'));
                    });

                    //倒计时
                    if (!isInit) {
                        startCount();
                        isInit = true;
                    }
                }
            });
        };

        questInit(questArea.data('url'));

    });

    //#endregion

    //#region page-learn-history

    $(document).on('pageInit', '#page-learn-history', function (e, id, page) {
        gridInit(page);
    });

    //#endregion

    //#region page-student-audits

    $(document).on('pageInit', '#page-student-audits', function (e, id, page) {
        gridInit(page);
    });

    //#endregion

    
    $.init();
});
